/*
 * Copyright (c) InContent.
 * Author: Val
 * Modified At: 16-3-15 下午2:22
 */

package org.alfalfa.datawarehouse;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author : Val
 * @Created : 2015-05-07
 * @E-mail : valer@126.com
 * @Version : 1.0
 */
@Component
public class DWManager {

	@Value("${mongodb.ip}")
	private static String ip;

	@Value("${mongodb.port}")
	private static String port;

	private static MongoClient mongoClient;
	private static String HAYDAYBOT_SCORE = "HAYDAY_BOT";

	private synchronized static MongoClient getMongoClient() {

		if (StringUtils.isBlank(ip)) ip = "localhost";
		if (StringUtils.isBlank(port)) port = "27017";


		if (mongoClient != null) return mongoClient;
		mongoClient = new MongoClient(ip, Integer.parseInt(port));
		return mongoClient;
	}

	private static MongoCollection<Document> getCollection(String namespace) {
		if (StringUtils.isBlank(namespace)) namespace = "__DEFAULT";
		return getMongoClient().getDatabase("test").getCollection(HAYDAYBOT_SCORE + "." + namespace);
	}

	public static DWHook getHook(String namespace) {
		return new DWHook(getCollection(namespace));
	}

}
